package com.cencat.product.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cencat.common.enums.ErrorCode;
import com.cencat.common.exception.BusinessException;
import com.cencat.common.response.ApiResponse;
import com.cencat.product.dto.ProductCreateDTO;
import com.cencat.product.dto.ProductQueryDTO;
import com.cencat.product.dto.ProductUpdateDTO;
import com.cencat.product.entity.Product;
import com.cencat.product.service.ProductService;
import com.cencat.product.vo.ProductVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 产品管理控制器
 * 
 * @author cencat
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/api/product")
@Tag(name = "产品管理", description = "产品管理相关接口")
@Slf4j
@Validated
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 创建产品
     * 
     * @param dto 产品创建DTO
     * @return 产品ID
     */
    @PostMapping("/create")
    @Operation(summary = "创建产品", description = "创建新的产品")
    public ApiResponse<Long> createProduct(@Valid @RequestBody ProductCreateDTO dto) {
        try {
            Long productId = productService.createProduct(dto);
            return ApiResponse.success(productId);
        } catch (BusinessException e) {
            log.error("创建产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("创建产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 更新产品
     * 
     * @param dto 产品更新DTO
     * @return 是否成功
     */
    @PutMapping("/update")
    @Operation(summary = "更新产品", description = "更新产品信息")
    public ApiResponse<Boolean> updateProduct(@Valid @RequestBody ProductUpdateDTO dto) {
        try {
            Boolean result = productService.updateProduct(dto);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("更新产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("更新产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 删除产品
     * 
     * @param id 产品ID
     * @return 是否成功
     */
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除产品", description = "删除指定产品")
    public ApiResponse<Boolean> deleteProduct(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id) {
        try {
            Boolean result = productService.deleteProduct(id);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("删除产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("删除产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 批量删除产品
     * 
     * @param ids 产品ID列表
     * @return 是否成功
     */
    @DeleteMapping("/batch-delete")
    @Operation(summary = "批量删除产品", description = "批量删除指定产品")
    public ApiResponse<Boolean> batchDeleteProducts(
            @Parameter(description = "产品ID列表", required = true)
            @RequestBody @NotEmpty List<Long> ids) {
        try {
            Boolean result = productService.batchDeleteProducts(ids);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量删除产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量删除产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据ID获取产品
     * 
     * @param id 产品ID
     * @return 产品信息
     */
    @GetMapping("/get/{id}")
    @Operation(summary = "获取产品", description = "根据ID获取产品信息")
    public ApiResponse<Product> getProductById(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id) {
        try {
            Product product = productService.getProductById(id);
            return ApiResponse.success(product);
        } catch (BusinessException e) {
            log.error("获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据编码获取产品
     * 
     * @param productCode 产品编码
     * @return 产品信息
     */
    @GetMapping("/get-by-code/{productCode}")
    @Operation(summary = "根据编码获取产品", description = "根据产品编码获取产品信息")
    public ApiResponse<Product> getProductByCode(
            @Parameter(description = "产品编码", required = true)
            @PathVariable @NotBlank String productCode) {
        try {
            Product product = productService.getProductByCode(productCode);
            return ApiResponse.success(product);
        } catch (BusinessException e) {
            log.error("根据编码获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据编码获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取产品详情
     * 
     * @param id 产品ID
     * @return 产品详情
     */
    @GetMapping("/detail/{id}")
    @Operation(summary = "获取产品详情", description = "获取产品详细信息")
    public ApiResponse<ProductVO> getProductDetail(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id) {
        try {
            ProductVO productVO = productService.getProductDetail(id);
            return ApiResponse.success(productVO);
        } catch (BusinessException e) {
            log.error("获取产品详情失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取产品详情异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 分页查询产品
     * 
     * @param queryDTO 查询条件
     * @return 产品分页列表
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询产品", description = "根据条件分页查询产品列表")
    public ApiResponse<IPage<ProductVO>> getProductPage(@Valid @RequestBody ProductQueryDTO queryDTO) {
        try {
            IPage<ProductVO> page = productService.getProductPage(queryDTO);
            return ApiResponse.success(page);
        } catch (BusinessException e) {
            log.error("分页查询产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("分页查询产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 查询产品列表
     * 
     * @param queryDTO 查询条件
     * @return 产品列表
     */
    @PostMapping("/list")
    @Operation(summary = "查询产品列表", description = "根据条件查询产品列表")
    public ApiResponse<List<ProductVO>> getProductList(@Valid @RequestBody ProductQueryDTO queryDTO) {
        try {
            List<ProductVO> list = productService.getProductList(queryDTO);
            return ApiResponse.success(list);
        } catch (BusinessException e) {
            log.error("查询产品列表失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("查询产品列表异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 上架产品
     * 
     * @param id 产品ID
     * @return 是否成功
     */
    @PutMapping("/on-shelf/{id}")
    @Operation(summary = "上架产品", description = "将产品设置为上架状态")
    public ApiResponse<Boolean> onShelfProduct(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id) {
        try {
            Boolean result = productService.onShelfProduct(id);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("上架产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("上架产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 下架产品
     * 
     * @param id 产品ID
     * @return 是否成功
     */
    @PutMapping("/off-shelf/{id}")
    @Operation(summary = "下架产品", description = "将产品设置为下架状态")
    public ApiResponse<Boolean> offShelfProduct(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id) {
        try {
            Boolean result = productService.offShelfProduct(id);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("下架产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("下架产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 批量上架产品
     * 
     * @param ids 产品ID列表
     * @return 是否成功
     */
    @PutMapping("/batch-on-shelf")
    @Operation(summary = "批量上架产品", description = "批量将产品设置为上架状态")
    public ApiResponse<Boolean> batchOnShelfProducts(
            @Parameter(description = "产品ID列表", required = true)
            @RequestBody @NotEmpty List<Long> ids) {
        try {
            Boolean result = productService.batchOnShelfProducts(ids);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量上架产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量上架产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 批量下架产品
     * 
     * @param ids 产品ID列表
     * @return 是否成功
     */
    @PutMapping("/batch-off-shelf")
    @Operation(summary = "批量下架产品", description = "批量将产品设置为下架状态")
    public ApiResponse<Boolean> batchOffShelfProducts(
            @Parameter(description = "产品ID列表", required = true)
            @RequestBody @NotEmpty List<Long> ids) {
        try {
            Boolean result = productService.batchOffShelfProducts(ids);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量下架产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量下架产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 审核产品
     * 
     * @param id 产品ID
     * @param auditStatus 审核状态
     * @param auditRemark 审核备注
     * @return 是否成功
     */
    @PutMapping("/audit/{id}")
    @Operation(summary = "审核产品", description = "审核产品")
    public ApiResponse<Boolean> auditProduct(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "审核状态", required = true)
            @RequestParam @NotNull Product.AuditStatus auditStatus,
            @Parameter(description = "审核备注")
            @RequestParam(required = false) String auditRemark) {
        try {
            Boolean result = productService.auditProduct(id, auditStatus, auditRemark);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("审核产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("审核产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 批量审核产品
     * 
     * @param ids 产品ID列表
     * @param auditStatus 审核状态
     * @param auditRemark 审核备注
     * @return 是否成功
     */
    @PutMapping("/batch-audit")
    @Operation(summary = "批量审核产品", description = "批量审核产品")
    public ApiResponse<Boolean> batchAuditProducts(
            @Parameter(description = "产品ID列表", required = true)
            @RequestParam @NotEmpty List<Long> ids,
            @Parameter(description = "审核状态", required = true)
            @RequestParam @NotNull Product.AuditStatus auditStatus,
            @Parameter(description = "审核备注")
            @RequestParam(required = false) String auditRemark) {
        try {
            Boolean result = productService.batchAuditProducts(ids, auditStatus, auditRemark);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量审核产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量审核产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 更新产品库存
     * 
     * @param id 产品ID
     * @param stockQuantity 库存数量
     * @return 是否成功
     */
    @PutMapping("/update-stock/{id}")
    @Operation(summary = "更新产品库存", description = "更新产品库存数量")
    public ApiResponse<Boolean> updateProductStock(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "库存数量", required = true)
            @RequestParam @NotNull @Min(0) Integer stockQuantity) {
        try {
            Boolean result = productService.updateProductStock(id, stockQuantity);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("更新产品库存失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("更新产品库存异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 增加产品库存
     * 
     * @param id 产品ID
     * @param quantity 增加数量
     * @return 是否成功
     */
    @PutMapping("/increase-stock/{id}")
    @Operation(summary = "增加产品库存", description = "增加产品库存数量")
    public ApiResponse<Boolean> increaseProductStock(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "增加数量", required = true)
            @RequestParam @NotNull @Min(1) Integer quantity) {
        try {
            Boolean result = productService.increaseProductStock(id, quantity);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("增加产品库存失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("增加产品库存异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 减少产品库存
     * 
     * @param id 产品ID
     * @param quantity 减少数量
     * @return 是否成功
     */
    @PutMapping("/decrease-stock/{id}")
    @Operation(summary = "减少产品库存", description = "减少产品库存数量")
    public ApiResponse<Boolean> decreaseProductStock(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "减少数量", required = true)
            @RequestParam @NotNull @Min(1) Integer quantity) {
        try {
            Boolean result = productService.decreaseProductStock(id, quantity);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("减少产品库存失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("减少产品库存异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取推荐产品
     * 
     * @param limit 数量限制
     * @return 推荐产品列表
     */
    @GetMapping("/recommended")
    @Operation(summary = "获取推荐产品", description = "获取推荐产品列表")
    public ApiResponse<List<ProductVO>> getRecommendedProducts(
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductVO> products = productService.getRecommendedProducts(limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取推荐产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取推荐产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取热门产品
     * 
     * @param limit 数量限制
     * @return 热门产品列表
     */
    @GetMapping("/hot")
    @Operation(summary = "获取热门产品", description = "获取热门产品列表")
    public ApiResponse<List<ProductVO>> getHotProducts(
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductVO> products = productService.getHotProducts(limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取热门产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取热门产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取新品产品
     * 
     * @param limit 数量限制
     * @return 新品产品列表
     */
    @GetMapping("/new")
    @Operation(summary = "获取新品产品", description = "获取新品产品列表")
    public ApiResponse<List<ProductVO>> getNewProducts(
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductVO> products = productService.getNewProducts(limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取新品产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取新品产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取特价产品
     * 
     * @param limit 数量限制
     * @return 特价产品列表
     */
    @GetMapping("/special")
    @Operation(summary = "获取特价产品", description = "获取特价产品列表")
    public ApiResponse<List<ProductVO>> getSpecialProducts(
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductVO> products = productService.getSpecialProducts(limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取特价产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取特价产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据商家ID获取产品
     * 
     * @param merchantId 商家ID
     * @return 产品列表
     */
    @GetMapping("/merchant/{merchantId}")
    @Operation(summary = "根据商家获取产品", description = "根据商家ID获取产品列表")
    public ApiResponse<List<ProductVO>> getProductsByMerchantId(
            @Parameter(description = "商家ID", required = true)
            @PathVariable @NotNull @Min(1) Long merchantId) {
        try {
            List<ProductVO> products = productService.getProductsByMerchantId(merchantId);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("根据商家获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据商家获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据分类ID获取产品
     * 
     * @param categoryId 分类ID
     * @return 产品列表
     */
    @GetMapping("/category/{categoryId}")
    @Operation(summary = "根据分类获取产品", description = "根据分类ID获取产品列表")
    public ApiResponse<List<ProductVO>> getProductsByCategoryId(
            @Parameter(description = "分类ID", required = true)
            @PathVariable @NotNull @Min(1) Long categoryId) {
        try {
            List<ProductVO> products = productService.getProductsByCategoryId(categoryId);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("根据分类获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据分类获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据品牌ID获取产品
     * 
     * @param brandId 品牌ID
     * @return 产品列表
     */
    @GetMapping("/brand/{brandId}")
    @Operation(summary = "根据品牌获取产品", description = "根据品牌ID获取产品列表")
    public ApiResponse<List<ProductVO>> getProductsByBrandId(
            @Parameter(description = "品牌ID", required = true)
            @PathVariable @NotNull @Min(1) Long brandId) {
        try {
            List<ProductVO> products = productService.getProductsByBrandId(brandId);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("根据品牌获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据品牌获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据价格范围获取产品
     * 
     * @param minPrice 最低价格
     * @param maxPrice 最高价格
     * @return 产品列表
     */
    @GetMapping("/price-range")
    @Operation(summary = "根据价格范围获取产品", description = "根据价格范围获取产品列表")
    public ApiResponse<List<ProductVO>> getProductsByPriceRange(
            @Parameter(description = "最低价格", required = true)
            @RequestParam @NotNull BigDecimal minPrice,
            @Parameter(description = "最高价格", required = true)
            @RequestParam @NotNull BigDecimal maxPrice) {
        try {
            List<ProductVO> products = productService.getProductsByPriceRange(minPrice, maxPrice);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("根据价格范围获取产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据价格范围获取产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 搜索产品
     * 
     * @param keyword 关键词
     * @param limit 数量限制
     * @return 产品列表
     */
    @GetMapping("/search")
    @Operation(summary = "搜索产品", description = "根据关键词搜索产品")
    public ApiResponse<List<ProductVO>> searchProducts(
            @Parameter(description = "搜索关键词", required = true)
            @RequestParam @NotBlank String keyword,
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "20") Integer limit) {
        try {
            List<ProductVO> products = productService.searchProducts(keyword, limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("搜索产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("搜索产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取相关产品
     * 
     * @param productId 产品ID
     * @param limit 数量限制
     * @return 相关产品列表
     */
    @GetMapping("/related/{productId}")
    @Operation(summary = "获取相关产品", description = "获取相关产品列表")
    public ApiResponse<List<ProductVO>> getRelatedProducts(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long productId,
            @Parameter(description = "数量限制")
            @RequestParam(required = false, defaultValue = "10") Integer limit) {
        try {
            List<ProductVO> products = productService.getRelatedProducts(productId, limit);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取相关产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取相关产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取即将过期产品
     * 
     * @param days 天数
     * @return 即将过期产品列表
     */
    @GetMapping("/expiring")
    @Operation(summary = "获取即将过期产品", description = "获取即将过期产品列表")
    public ApiResponse<List<ProductVO>> getExpiringProducts(
            @Parameter(description = "天数")
            @RequestParam(required = false, defaultValue = "7") Integer days) {
        try {
            List<ProductVO> products = productService.getExpiringProducts(days);
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取即将过期产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取即将过期产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取已过期产品
     * 
     * @return 已过期产品列表
     */
    @GetMapping("/expired")
    @Operation(summary = "获取已过期产品", description = "获取已过期产品列表")
    public ApiResponse<List<ProductVO>> getExpiredProducts() {
        try {
            List<ProductVO> products = productService.getExpiredProducts();
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取已过期产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取已过期产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取低库存产品
     * 
     * @return 低库存产品列表
     */
    @GetMapping("/low-stock")
    @Operation(summary = "获取低库存产品", description = "获取低库存产品列表")
    public ApiResponse<List<ProductVO>> getLowStockProducts() {
        try {
            List<ProductVO> products = productService.getLowStockProducts();
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取低库存产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取低库存产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取缺货产品
     * 
     * @return 缺货产品列表
     */
    @GetMapping("/sold-out")
    @Operation(summary = "获取缺货产品", description = "获取缺货产品列表")
    public ApiResponse<List<ProductVO>> getSoldOutProducts() {
        try {
            List<ProductVO> products = productService.getSoldOutProducts();
            return ApiResponse.success(products);
        } catch (BusinessException e) {
            log.error("获取缺货产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取缺货产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 统计产品总数
     * 
     * @return 产品总数
     */
    @GetMapping("/count/total")
    @Operation(summary = "统计产品总数", description = "统计产品总数")
    public ApiResponse<Long> countTotalProducts() {
        try {
            Long count = productService.countTotalProducts();
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("统计产品总数失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("统计产品总数异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据状态统计产品数量
     * 
     * @param status 产品状态
     * @return 产品数量
     */
    @GetMapping("/count/status")
    @Operation(summary = "根据状态统计产品数量", description = "根据状态统计产品数量")
    public ApiResponse<Long> countProductsByStatus(
            @Parameter(description = "产品状态", required = true)
            @RequestParam @NotNull Product.ProductStatus status) {
        try {
            Long count = productService.countProductsByStatus(status);
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("根据状态统计产品数量失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据状态统计产品数量异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据类型统计产品数量
     * 
     * @param productType 产品类型
     * @return 产品数量
     */
    @GetMapping("/count/type")
    @Operation(summary = "根据类型统计产品数量", description = "根据类型统计产品数量")
    public ApiResponse<Long> countProductsByType(
            @Parameter(description = "产品类型", required = true)
            @RequestParam @NotNull Product.ProductType productType) {
        try {
            Long count = productService.countProductsByType(productType);
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("根据类型统计产品数量失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据类型统计产品数量异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 根据审核状态统计产品数量
     * 
     * @param auditStatus 审核状态
     * @return 产品数量
     */
    @GetMapping("/count/audit-status")
    @Operation(summary = "根据审核状态统计产品数量", description = "根据审核状态统计产品数量")
    public ApiResponse<Long> countProductsByAuditStatus(
            @Parameter(description = "审核状态", required = true)
            @RequestParam @NotNull Product.AuditStatus auditStatus) {
        try {
            Long count = productService.countProductsByAuditStatus(auditStatus);
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("根据审核状态统计产品数量失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("根据审核状态统计产品数量异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 统计低库存产品数量
     * 
     * @return 低库存产品数量
     */
    @GetMapping("/count/low-stock")
    @Operation(summary = "统计低库存产品数量", description = "统计低库存产品数量")
    public ApiResponse<Long> countLowStockProducts() {
        try {
            Long count = productService.countLowStockProducts();
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("统计低库存产品数量失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("统计低库存产品数量异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 统计缺货产品数量
     * 
     * @return 缺货产品数量
     */
    @GetMapping("/count/sold-out")
    @Operation(summary = "统计缺货产品数量", description = "统计缺货产品数量")
    public ApiResponse<Long> countSoldOutProducts() {
        try {
            Long count = productService.countSoldOutProducts();
            return ApiResponse.success(count);
        } catch (BusinessException e) {
            log.error("统计缺货产品数量失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("统计缺货产品数量异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取商家产品统计
     * 
     * @param merchantId 商家ID
     * @return 统计信息
     */
    @GetMapping("/stats/merchant/{merchantId}")
    @Operation(summary = "获取商家产品统计", description = "获取商家产品统计信息")
    public ApiResponse<Map<String, Object>> getMerchantProductStats(
            @Parameter(description = "商家ID", required = true)
            @PathVariable @NotNull @Min(1) Long merchantId) {
        try {
            Map<String, Object> stats = productService.getMerchantProductStats(merchantId);
            return ApiResponse.success(stats);
        } catch (BusinessException e) {
            log.error("获取商家产品统计失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取商家产品统计异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取分类产品统计
     * 
     * @param categoryId 分类ID
     * @return 统计信息
     */
    @GetMapping("/stats/category/{categoryId}")
    @Operation(summary = "获取分类产品统计", description = "获取分类产品统计信息")
    public ApiResponse<Map<String, Object>> getCategoryProductStats(
            @Parameter(description = "分类ID", required = true)
            @PathVariable @NotNull @Min(1) Long categoryId) {
        try {
            Map<String, Object> stats = productService.getCategoryProductStats(categoryId);
            return ApiResponse.success(stats);
        } catch (BusinessException e) {
            log.error("获取分类产品统计失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取分类产品统计异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取品牌产品统计
     * 
     * @param brandId 品牌ID
     * @return 统计信息
     */
    @GetMapping("/stats/brand/{brandId}")
    @Operation(summary = "获取品牌产品统计", description = "获取品牌产品统计信息")
    public ApiResponse<Map<String, Object>> getBrandProductStats(
            @Parameter(description = "品牌ID", required = true)
            @PathVariable @NotNull @Min(1) Long brandId) {
        try {
            Map<String, Object> stats = productService.getBrandProductStats(brandId);
            return ApiResponse.success(stats);
        } catch (BusinessException e) {
            log.error("获取品牌产品统计失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取品牌产品统计异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取产品销售统计
     * 
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 销售统计
     */
    @GetMapping("/stats/sales")
    @Operation(summary = "获取产品销售统计", description = "获取产品销售统计信息")
    public ApiResponse<List<Map<String, Object>>> getProductSalesStats(
            @Parameter(description = "开始时间", required = true)
            @RequestParam @NotNull LocalDateTime startTime,
            @Parameter(description = "结束时间", required = true)
            @RequestParam @NotNull LocalDateTime endTime) {
        try {
            List<Map<String, Object>> stats = productService.getProductSalesStats(startTime, endTime);
            return ApiResponse.success(stats);
        } catch (BusinessException e) {
            log.error("获取产品销售统计失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取产品销售统计异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取产品库存统计
     * 
     * @return 库存统计
     */
    @GetMapping("/stats/stock")
    @Operation(summary = "获取产品库存统计", description = "获取产品库存统计信息")
    public ApiResponse<Map<String, Object>> getProductStockStats() {
        try {
            Map<String, Object> stats = productService.getProductStockStats();
            return ApiResponse.success(stats);
        } catch (BusinessException e) {
            log.error("获取产品库存统计失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("获取产品库存统计异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 生成产品编码
     * 
     * @param prefix 前缀
     * @return 产品编码
     */
    @GetMapping("/generate-code")
    @Operation(summary = "生成产品编码", description = "生成产品编码")
    public ApiResponse<String> generateProductCode(
            @Parameter(description = "编码前缀")
            @RequestParam(required = false, defaultValue = "PRD") String prefix) {
        try {
            String productCode = productService.generateProductCode(prefix);
            return ApiResponse.success(productCode);
        } catch (BusinessException e) {
            log.error("生成产品编码失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("生成产品编码异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 检查产品编码是否存在
     * 
     * @param productCode 产品编码
     * @param excludeId 排除的产品ID
     * @return 是否存在
     */
    @GetMapping("/check-code")
    @Operation(summary = "检查产品编码是否存在", description = "检查产品编码是否存在")
    public ApiResponse<Boolean> checkProductCodeExists(
            @Parameter(description = "产品编码", required = true)
            @RequestParam @NotBlank String productCode,
            @Parameter(description = "排除的产品ID")
            @RequestParam(required = false) Long excludeId) {
        try {
            Boolean exists = productService.checkProductCodeExists(productCode, excludeId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查产品编码是否存在失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查产品编码是否存在异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 检查产品名称是否存在
     * 
     * @param productName 产品名称
     * @param excludeId 排除的产品ID
     * @return 是否存在
     */
    @GetMapping("/check-name")
    @Operation(summary = "检查产品名称是否存在", description = "检查产品名称是否存在")
    public ApiResponse<Boolean> checkProductNameExists(
            @Parameter(description = "产品名称", required = true)
            @RequestParam @NotBlank String productName,
            @Parameter(description = "排除的产品ID")
            @RequestParam(required = false) Long excludeId) {
        try {
            Boolean exists = productService.checkProductNameExists(productName, excludeId);
            return ApiResponse.success(exists);
        } catch (BusinessException e) {
            log.error("检查产品名称是否存在失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("检查产品名称是否存在异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 复制产品
     * 
     * @param id 原产品ID
     * @param newProductName 新产品名称
     * @param newProductCode 新产品编码
     * @return 新产品ID
     */
    @PostMapping("/copy/{id}")
    @Operation(summary = "复制产品", description = "复制产品")
    public ApiResponse<Long> copyProduct(
            @Parameter(description = "原产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "新产品名称", required = true)
            @RequestParam @NotBlank String newProductName,
            @Parameter(description = "新产品编码", required = true)
            @RequestParam @NotBlank String newProductCode) {
        try {
            Long newProductId = productService.copyProduct(id, newProductName, newProductCode);
            return ApiResponse.success(newProductId);
        } catch (BusinessException e) {
            log.error("复制产品失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("复制产品异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 设置产品推荐状态
     * 
     * @param id 产品ID
     * @param isRecommended 是否推荐
     * @return 是否成功
     */
    @PutMapping("/set-recommended/{id}")
    @Operation(summary = "设置产品推荐状态", description = "设置产品推荐状态")
    public ApiResponse<Boolean> setProductRecommended(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "是否推荐", required = true)
            @RequestParam @NotNull Boolean isRecommended) {
        try {
            Boolean result = productService.setProductRecommended(id, isRecommended);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置产品推荐状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置产品推荐状态异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 设置产品热门状态
     * 
     * @param id 产品ID
     * @param isHot 是否热门
     * @return 是否成功
     */
    @PutMapping("/set-hot/{id}")
    @Operation(summary = "设置产品热门状态", description = "设置产品热门状态")
    public ApiResponse<Boolean> setProductHot(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "是否热门", required = true)
            @RequestParam @NotNull Boolean isHot) {
        try {
            Boolean result = productService.setProductHot(id, isHot);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置产品热门状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置产品热门状态异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 设置产品新品状态
     * 
     * @param id 产品ID
     * @param isNew 是否新品
     * @return 是否成功
     */
    @PutMapping("/set-new/{id}")
    @Operation(summary = "设置产品新品状态", description = "设置产品新品状态")
    public ApiResponse<Boolean> setProductNew(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "是否新品", required = true)
            @RequestParam @NotNull Boolean isNew) {
        try {
            Boolean result = productService.setProductNew(id, isNew);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置产品新品状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置产品新品状态异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 设置产品特价状态
     * 
     * @param id 产品ID
     * @param isSpecial 是否特价
     * @return 是否成功
     */
    @PutMapping("/set-special/{id}")
    @Operation(summary = "设置产品特价状态", description = "设置产品特价状态")
    public ApiResponse<Boolean> setProductSpecial(
            @Parameter(description = "产品ID", required = true)
            @PathVariable @NotNull @Min(1) Long id,
            @Parameter(description = "是否特价", required = true)
            @RequestParam @NotNull Boolean isSpecial) {
        try {
            Boolean result = productService.setProductSpecial(id, isSpecial);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("设置产品特价状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("设置产品特价状态异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 批量更新产品状态
     * 
     * @param ids 产品ID列表
     * @param status 产品状态
     * @return 是否成功
     */
    @PutMapping("/batch-update-status")
    @Operation(summary = "批量更新产品状态", description = "批量更新产品状态")
    public ApiResponse<Boolean> batchUpdateProductStatus(
            @Parameter(description = "产品ID列表", required = true)
            @RequestParam @NotEmpty List<Long> ids,
            @Parameter(description = "产品状态", required = true)
            @RequestParam @NotNull Product.ProductStatus status) {
        try {
            Boolean result = productService.batchUpdateProductStatus(ids, status);
            return ApiResponse.success(result);
        } catch (BusinessException e) {
            log.error("批量更新产品状态失败: {}", e.getMessage());
            return ApiResponse.error(e.getErrorCode());
        } catch (Exception e) {
            log.error("批量更新产品状态异常", e);
            return ApiResponse.error(ErrorCode.SYSTEM_ERROR);
        }
    }
}